import axios from 'axios'
import { BASE_URL, TIMEOUT } from "./config.js"
import useMainStore from '@/stores/modules/main.js'
import { storeToRefs } from 'pinia'

const mainStore = useMainStore()
const { isLoading } = storeToRefs(mainStore)

class HYRequest {
    constructor(baseURL, timeout = 10000) {
        this.instance = axios.create({
            baseURL,
            timeout
        })

        this.instance.interceptors.request.use((config) => {
            mainStore.isLoading = true
            // 在发送请求之前做些什么
            return config
        }, (err) => {
            // 对请求错误做些什么
            return Promise.reject(err)
        })

        this.instance.interceptors.response.use(response => {

            mainStore.isLoading = false
            // 对响应数据做点什么
            return response
        }, err => {
            
            mainStore.isLoading = false
            // 对响应错误做点什么
            return Promise.reject(err)
        })
    }

    request(config) {
        // 在请求之前为true
        // mainStore.isLoading = true;
        return new Promise((resolve, reject) => {
            this.instance.request(config).then(res => {
                // 在请求之后为false
                // mainStore.isLoading = false;
                resolve(res.data)
            }).catch(err => {
                // mainStore.isLoading = false;
                reject(err)
            })
        })
    }

    get(config) {
        return this.request({ ...config, method: "get" })
    }

    post(config) {
        return this.request({ ...config, method: "post" })
    }
}

export default new HYRequest(BASE_URL, TIMEOUT)